#include<iostream>
#include<unistd.h>
#include<cerrno>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

const int size =1024;

string getOtherMessage()
{
    static int cnt=0;
    string messageid =to_string(cnt);
    cnt++;
    pid_t self_id=getpid();
    string stringpid=to_string(self_id);

    string message ="messageid: ";
    message+=messageid;
    message+=stringpid;

    return message;
}
//子进程进行写入    
void SubProcWrite(int wfd)
{
    int pipesize=0;
    string message="father,I am your son process ";
    while(true)
    {
        // string info =message + getOtherMessage()+'\n';//子进程发给父进程的消息
        // write(wfd,info.c_str(),info.size());
        // sleep(5); //子进程写慢一点


        //测试管道大小
        char c='A';
        write(wfd,&c,1);
        cout<<"pipesize: "<<++pipesize<<endl;

    }
}

//父进程进行读取
void FatherProcRead(int rfd)
{
    char inbuffer[size];
    while(true)
    {
        sleep(500);
        ssize_t n=read(rfd,inbuffer,sizeof(inbuffer)-1);
        if(n>0)
        {
            inbuffer[n]=0;
            cout<<"father get message:"<<inbuffer<<endl;
        }
    }
}


int main()
{
    //1.创建管道
    int pipefd[2];
    int n =pipe(pipefd);
    if(n!=0)
    {
        cout<<"errno:"<<errno<<":"<<"errstring:"<<strerror(errno)<<endl;
        return 1;
    }

    //pipefd[0]->0->r   pipefd[1]->1->w
    cout<<"pipefd[0]:"<<pipefd[0]<<",pipefd[1]:"<<pipefd[1]<<endl;

    //2.创建子进程
    pid_t id =fork();
    if(id==0)
    {
        
        //子进程---write
        //3.关闭不需要的fd
        cout<<"子进程关闭不需要的fd了，准备发送消息"<<endl;
        sleep(1);

        close(pipefd[0]);
        SubProcWrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }

    //父进程---read
    //3.关闭不需要的fd
    cout<<"父进程关闭不需要的fd了，准备接受消息"<<endl;
    sleep(1);

    close(pipefd[1]);
    FatherProcRead(pipefd[0]);
    close(pipefd[0]);


    pid_t rid=waitpid(id,nullptr,0);
    if(rid>0)
    {
        cout<<"wait child process done"<<endl;
    }

    return 0;
}